﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Lenovo.CFI.BLL;
using Lenovo.CFI.BLL.DicMgr;
using Lenovo.CFI.BLL.Sys;
using Lenovo.CFI.Common;
using Lenovo.CFI.Web.Helper;
using Lenovo.CFI.Common.Sys;

namespace Lenovo.CFI.Web.VP
{
    public partial class Search : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindHelper.BindTopics(this.DdlTopic, "Select...", "-1", null);
                BindHelper.BindIdeaType(this.DdlType, "Select...", "", null, true);
                BindHelper.BindIdeaType(this.CbRelatedType, null, null, null, true);
                BindHelper.BindKeyword(this.LbKeywords, null, null, null, true);
                BindHelper.BindTeam(this.DdlTeamOwner, "Select...", "-1", null);
                BindHelper.BindNextAction(this.DdlNextAction, "Select...", "", null, true);

                this.DpTopicDateF.Value = "";
                this.DpTopicDateT.Value = "";
                this.DpSubmitDateF.Value = "";
                this.DpSubmitDateT.Value = "";


                // 是否限制
                if (UserHelper.HasAccessPerm(UserRole.ROLE_ADMIN.ToString()) ||
                    UserHelper.HasAccessPerm(UserRole.ROLE_ASSISTANT1.ToString()) ||
                    UserHelper.HasAccessPerm(UserRole.ROLE_ASSISTANT2.ToString()) ||
                    UserHelper.HasAccessPerm(UserRole.ROLE_MGR.ToString()) ||
                    UserHelper.HasAccessPerm(UserRole.ROLE_VP.ToString()) ||
                    UserHelper.HasAccessPerm(UserRole.ROLE_DC.ToString()) ||
                    UserHelper.HasAccessPerm(UserRole.ROLE_IP.ToString()))
                    ViewState["user"] = null;
                else
                {
                    ViewState["user"] = UserHelper.UserName;

                    this.BtnExport.Visible = false;     // 不允许导出
                }


                // 获取传入参数
                bool stat = (UrlHelper.GetQueryString("stat") == "1");
                int? topicID = UrlHelper.GetQueryStringToInt("topicid");
                string finalType = UrlHelper.GetQueryString("type");
                string finalAction = UrlHelper.GetQueryString("action");
                string topicDateF = UrlHelper.GetQueryString("topicdf");
                string topicDateT = UrlHelper.GetQueryString("topicdt");
                bool award = (UrlHelper.GetQueryString("award") == "1");
                bool ip = (UrlHelper.GetQueryString("ip") == "1");
                int? ips = UrlHelper.GetQueryStringToInt("ips");
                int? ideaTeamID = UrlHelper.GetQueryStringToInt("teamid");
                int? ownerTeamID = UrlHelper.GetQueryStringToInt("teamido");
                string ideaTeamManagerCurrent = UrlHelper.GetQueryString("managerc");
                string ideaTeamVPCurrent = UrlHelper.GetQueryString("vpc");


                ViewState["topicid"] = topicID;
                ViewState["type"] = finalType;
                ViewState["nextaction"] = finalAction;
                if (!String.IsNullOrEmpty(topicDateF)) { this.DpTopicDateF.Value = topicDateF; this.DpTopicDateF.Save(); }
                if (!String.IsNullOrEmpty(topicDateT)) { this.DpTopicDateT.Value = topicDateT; this.DpTopicDateT.Save(); }
                if (award) ViewState["award"] = 0;
                if (ip) ViewState["ip"] = 1;
                if (ips.HasValue) ViewState["ips"] = ips;
                if (ideaTeamID.HasValue) ViewState["ideateamid"] = ideaTeamID.Value;
                if (ownerTeamID.HasValue) ViewState["ownerteamid"] = ownerTeamID.Value;
                if (!String.IsNullOrEmpty(ideaTeamManagerCurrent)) { ViewState["ideamanagercurrent"] = ideaTeamManagerCurrent; }
                if (!String.IsNullOrEmpty(ideaTeamVPCurrent)) { ViewState["ideavpcurrent"] = ideaTeamVPCurrent; }

                if (stat)
                {
                    this.FsSearch.Display = false;  // 默认不显示

                    this.BindData();
                }
                else
                    this.GvList.Visible = false;

                MessageHelper.Prepare(this.Page);
            }
            ScriptManager1.RegisterPostBackControl(BtnExport);
        }

        protected void BtnSearch_Click(object sender, EventArgs e)
        {
            ViewState["topicid"] = this.DdlTopic.SelectedValue;
            ViewState["type"] = this.DdlType.SelectedValue;
            ViewState["title"] = this.TxtName.Text.Trim();
            ViewState["status"] = this.DdlStatus.SelectedValue;

            string relatedTypes = "";
            foreach (ListItem item in this.CbRelatedType.Items)
            {
                if (item.Selected) relatedTypes += (item.Value + ";");
            }
            ViewState["relatedtype"] = relatedTypes;

            List<string> keywords = new List<string>();
            foreach (ListItem item in this.LbKeywords.Items)
            {
                if (item.Selected) keywords.Add(item.Value);
            }
            keywords.AddRange(CodeList.SplitStringToList(this.TxtKeywords.Text.Trim()));
            ViewState["keywords"] = CodeList.ConvertListToString(keywords);

            ViewState["owner"] = this.OuacOwner.Text.ToLower();
            ViewState["ownermanager"] = this.OuacManager.Text.ToLower();
            ViewState["ownervp"] = this.OuacVP.Text.ToLower();
            ViewState["ownerteamid"] = this.DdlTeamOwner.SelectedValue;

            ViewState["nextaction"] = this.DdlNextAction.SelectedValue;
            ViewState["actionstatus"] = this.DdlNextActionStatus.SelectedValue;
            ViewState["ip"] = this.DdlIP.SelectedValue;
            ViewState["ipstatus"] = this.DdlNextIPStatus.SelectedValue;

            this.DpTopicDateF.Save();
            this.DpTopicDateF.Save();
            this.DpSubmitDateF.Save();
            this.DpSubmitDateF.Save();

            this.BindData();
        }

        private void BindData()
        {
            this.BindData(true);
        }

        List<Idea> ideasData = null;
        Dictionary<int, IdeaReview> reviewsDic = null;
        private void BindData(bool bindlist)
        {
            int? topicID = null; if (ViewState["topicid"] != null) { topicID = Convert.ToInt32(ViewState["topicid"]); if (topicID == -1) topicID = null; }

            string finalType = null; if (ViewState["type"] != null) { finalType = (string)ViewState["type"]; if (finalType == String.Empty) finalType = null; }

            string title = null; if (ViewState["title"] != null) { title = (string)ViewState["title"]; if (title == String.Empty) title = null; }

            int? status = null; if (ViewState["status"] != null) { status = Convert.ToInt32(ViewState["status"]); if (status == -1) status = null; }
            List<int> multiStatus = null; if (status == -1) multiStatus = new List<int>(new int[] {31,41,51});

            List<string> relatedType = null; if (ViewState["relatedtype"] != null) relatedType = new List<string>(CodeList.SplitStringToList((string)ViewState["relatedtype"]));

            List<string> keywords = null; if (ViewState["keywords"] != null) keywords = new List<string>(CodeList.SplitStringToList((string)ViewState["keywords"]));

            string owner = null; if (ViewState["owner"] != null) { owner = (string)ViewState["owner"]; if (owner == String.Empty) owner = null; }
            int? ownerTeamID = null; if (ViewState["ownerteamid"] != null) { ownerTeamID = Convert.ToInt32(ViewState["ownerteamid"]); if (ownerTeamID == -1) ownerTeamID = null; }
            string ownerManager = null; if (ViewState["ownermanager"] != null) { ownerManager = (string)ViewState["ownermanager"]; if (ownerManager == String.Empty) ownerManager = null; }
            string ownerVP = null; if (ViewState["ownervp"] != null) { ownerVP = (string)ViewState["ownervp"]; if (ownerVP == String.Empty) ownerVP = null; }
            int? ideaTeamID = null; if (ViewState["ideateamid"] != null) { ideaTeamID = Convert.ToInt32(ViewState["ideateamid"]); if (ideaTeamID == -1) ideaTeamID = null; }
            string ideaTeamManagerCurrent = null; if (ViewState["ideamanagercurrent"] != null) { ideaTeamManagerCurrent = (string)ViewState["ideamanagercurrent"]; if (ideaTeamManagerCurrent == String.Empty) ideaTeamManagerCurrent = null; }
            string ideaTeamVPCurrent = null; if (ViewState["ideavpcurrent"] != null) { ideaTeamVPCurrent = (string)ViewState["ideavpcurrent"]; if (ideaTeamVPCurrent == String.Empty) ideaTeamVPCurrent = null; }

            
            string nextaction = null; if (ViewState["nextaction"] != null) { nextaction = (string)ViewState["nextaction"]; if (nextaction == String.Empty) nextaction = null; }
            int? actionStatus = null; if (ViewState["actionstatus"] != null) { actionStatus = Convert.ToInt32(ViewState["actionstatus"]); if (actionStatus == -1) actionStatus = null; }
            bool? ip = null; if (ViewState["ip"] != null)
            {
                switch (Convert.ToInt32(ViewState["ip"]))
                {
                    case -1:
                        ip = null;
                        break;
                    case 1:
                        ip = true;
                        break;
                    case 0:
                        ip = false;
                        break;

                }
            }
            int? ipStatus = null; if (ViewState["ipstatus"] != null) { ipStatus = Convert.ToInt32(ViewState["ipstatus"]); if (ipStatus == -1) ipStatus = null; }
            int? award = null; if (ViewState["award"] != null) { award = Convert.ToInt32(ViewState["award"]); if (award == -1) award = null; }
            int? ips = null; if (ViewState["ips"] != null) { ips = Convert.ToInt32(ViewState["ips"]);}
            //string user = null; if (ViewState["user"] != null) { user = (string)ViewState["user"]; if (user == String.Empty) user = null; }




            this.ideasData = new IdeaBl().SearchIdea(topicID, title, owner, ideaTeamID, ownerTeamID, null, ownerManager, ideaTeamManagerCurrent, null, ownerVP, ideaTeamVPCurrent,
                null, relatedType, keywords, (IdeaStatus?)status, multiStatus, true,
                this.DpSubmitDateF.SavedValue, this.DpSubmitDateT.SavedValue, this.DpTopicDateF.SavedValue, this.DpTopicDateT.SavedValue,
                finalType, null, nextaction, ip, actionStatus, ipStatus, null, null); // user);


            if (ips.HasValue)
            {
                if (ips.Value > 0)
                    this.ideasData = this.ideasData.FindAll(i => i.FinalIPStatus == (ExecutionStatus)ips);
                else
                    this.ideasData = this.ideasData.FindAll(i => i.FinalIPStatus != (ExecutionStatus)(-ips));
            }

            reviewsDic = new Dictionary<int, IdeaReview>();
            List<int> ids = new List<int>();
            foreach (Idea idea in ideasData) ids.Add(idea.FinalReviewID.Value);
            foreach (IdeaReview review in new ReviewBl().GetReviewByIDs(ids)) reviewsDic.Add(review.IdeaID, review);

            if (bindlist)
            {
                this.GvList.Visible = true;
                this.GvList.DataSource = ideasData;
                this.GvList.DataBind();
            }
        }

        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);

                Idea idea = (Idea)e.Row.DataItem;

                ((Literal)e.Row.FindControl("LtrTitle")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                    UrlHelper.GenerateUrl("ideadetail", "id", idea.ID.ToString(), "a", "1"), idea.Title);
                ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;
                ((Literal)e.Row.FindControl("LtrType")).Text = IdeaTypeDicMgr.GetByCode(idea.FinalType).Title;
                ((Literal)e.Row.FindControl("LtrNextAction")).Text = NextActionDicMgr.GetByCode(idea.FinalAction).Title;
            }
        }

        protected void GvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GvList.PageIndex = e.NewPageIndex;
            this.BindData();
        }


        protected void BtnExport_Click(object sender, EventArgs e)
        {
            this.BindData(false);

            FileDUHelper.Download("IdeaList.xls", IdeaBl.ExportIdeaList(this.ideasData, this.reviewsDic));
        }

        

        

        

        

    }
}